<template>
  <div class="route-observer-monitor">
    <el-card class="monitor-card">
      <template #header>
        <div class="card-header">
          <span>路由观察者监控</span>
          <el-switch 
            v-model="monitorEnabled" 
            @change="toggleMonitor"
            active-text="启用"
            inactive-text="禁用"
          />
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 当前路由状态 -->
        <el-tab-pane label="当前状态" name="current">
          <div class="status-section">
            <el-descriptions title="当前路由信息" :column="2" border>
              <el-descriptions-item label="路径">
                {{ currentRoute?.path || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="名称">
                {{ currentRoute?.name || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="完整路径">
                {{ currentRoute?.fullPath || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="时间戳">
                {{ currentRoute?.timestamp ? formatTime(currentRoute.timestamp) : '无' }}
              </el-descriptions-item>
            </el-descriptions>

            <el-divider content-position="left">面包屑导航</el-divider>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item 
                v-for="(item, index) in breadcrumbs" 
                :key="index"
                :to="item.path"
              >
                {{ item.name }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </el-tab-pane>

        <!-- 观察者列表 -->
        <el-tab-pane label="观察者" name="observers">
          <div class="observers-section">
            <el-alert 
              :title="`当前有 ${observerCount} 个活跃观察者`" 
              type="info" 
              :closable="false"
              style="margin-bottom: 16px"
            />
            
            <el-table :data="observerStats" stripe style="width: 100%">
              <el-table-column prop="name" label="观察者名称" width="200" />
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="updateCount" label="更新次数" width="100" />
              <el-table-column prop="lastUpdate" label="最后更新" width="180">
                <template #default="scope">
                  {{ scope.row.lastUpdate ? formatTime(scope.row.lastUpdate) : '无' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                    {{ scope.row.status === 'active' ? '活跃' : '异常' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 路由历史 -->
        <el-tab-pane label="导航历史" name="history">
          <div class="history-section">
            <div class="history-actions">
              <el-button @click="clearHistory" size="small" type="danger">
                清空历史
              </el-button>
              <el-button @click="exportHistory" size="small" type="primary">
                导出历史
              </el-button>
            </div>
            
            <el-timeline>
              <el-timeline-item
                v-for="(route, index) in routeHistory.slice().reverse()"
                :key="index"
                :timestamp="formatTime(route.timestamp)"
                placement="top"
              >
                <el-card shadow="hover" class="history-item">
                  <div class="route-info">
                    <div class="route-path">{{ route.path }}</div>
                    <div class="route-meta">
                      <span v-if="route.name">名称: {{ route.name }}</span>
                      <span v-if="route.from">来自: {{ route.from.path }}</span>
                    </div>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>

        <!-- 性能监控 -->
        <el-tab-pane label="性能监控" name="performance">
          <div class="performance-section">
            <el-row :gutter="16">
              <el-col :span="8">
                <el-statistic title="平均加载时间" :value="performanceData.averageLoadTime" suffix="ms" />
              </el-col>
              <el-col :span="8">
                <el-statistic title="导航次数" :value="totalNavigations" />
              </el-col>
              <el-col :span="8">
                <el-statistic title="慢速路由" :value="performanceData.slowRoutes.length" />
              </el-col>
            </el-row>

            <el-divider content-position="left">慢速路由</el-divider>
            <el-table :data="performanceData.slowRoutes" stripe style="width: 100%">
              <el-table-column prop="path" label="路径" />
              <el-table-column prop="loadTime" label="加载时间(ms)" width="120" />
              <el-table-column prop="timestamp" label="时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.timestamp) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 调试工具 -->
        <el-tab-pane label="调试工具" name="debug">
          <div class="debug-section">
            <el-button-group>
              <el-button @click="triggerTestUpdate" type="primary">
                触发测试更新
              </el-button>
              <el-button @click="simulateSlowRoute" type="warning">
                模拟慢速路由
              </el-button>
              <el-button @click="resetAllData" type="danger">
                重置所有数据
              </el-button>
            </el-button-group>

            <el-divider content-position="left">调试信息</el-divider>
            <el-card shadow="never">
              <pre class="debug-info">{{ JSON.stringify(debugInfo, null, 2) }}</pre>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouteStore } from '@/stores/route'
import { useRouteObserver, useRoutePerformance } from '@/composables/useRouteObserver'

const routeStore = useRouteStore()
const { 
  setupDefaultObservers, 
  getCurrentRoute, 
  getRouteHistory, 
  triggerUpdate 
} = useRouteObserver()

const { 
  performanceData, 
  setupPerformanceMonitoring, 
  clearPerformanceData 
} = useRoutePerformance()

// 响应式数据
const monitorEnabled = ref(true)
const activeTab = ref('current')
const observerCount = ref(0)
const observerStats = ref([])

// 计算属性
const currentRoute = computed(() => routeStore.currentRoute)
const breadcrumbs = computed(() => routeStore.breadcrumbs)
const routeHistory = computed(() => routeStore.routeHistory)

const totalNavigations = computed(() => {
  return Object.values(performanceData.value.navigationTimes)
    .reduce((total, times) => total + times.length, 0)
})

const debugInfo = computed(() => {
  return routeStore.getDebugInfo()
})

// 方法
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const toggleMonitor = (enabled) => {
  if (enabled) {
    setupDefaultObservers()
    setupPerformanceMonitoring()
  } else {
    // 这里可以添加禁用监控的逻辑
  }
}

const clearHistory = () => {
  routeStore.routeHistory = []
  ElMessage.success('历史记录已清空')
}

const exportHistory = () => {
  const data = JSON.stringify(routeHistory.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `route-history-${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('历史记录已导出')
}

const triggerTestUpdate = () => {
  const testRoute = {
    path: '/test',
    name: 'test',
    fullPath: '/test?debug=true',
    timestamp: Date.now(),
    from: { path: '/current', name: 'current' }
  }
  triggerUpdate(testRoute)
  ElMessage.success('测试更新已触发')
}

const simulateSlowRoute = () => {
  const slowRoute = {
    path: '/slow-route',
    name: 'slow',
    loadTime: 3000,
    timestamp: Date.now()
  }
  performanceData.value.slowRoutes.push(slowRoute)
  ElMessage.warning('已模拟慢速路由')
}

const resetAllData = () => {
  routeStore.routeHistory = []
  clearPerformanceData()
  observerStats.value = []
  ElMessage.success('所有数据已重置')
}

// 模拟观察者统计数据
const updateObserverStats = () => {
  observerStats.value = [
    { name: 'PageTitleObserver', type: '标题', updateCount: 15, lastUpdate: Date.now() - 5000, status: 'active' },
    { name: 'BreadcrumbObserver', type: '面包屑', updateCount: 12, lastUpdate: Date.now() - 3000, status: 'active' },
    { name: 'UserStateObserver', type: '用户状态', updateCount: 8, lastUpdate: Date.now() - 1000, status: 'active' },
    { name: 'CacheObserver', type: '缓存', updateCount: 20, lastUpdate: Date.now() - 500, status: 'active' },
    { name: 'RouteStateObserver', type: '状态同步', updateCount: 25, lastUpdate: Date.now() - 100, status: 'active' }
  ]
  observerCount.value = observerStats.value.length
}

// 监听路由变化
watch(currentRoute, (newRoute) => {
  if (newRoute) {
    updateObserverStats()
  }
}, { deep: true })

onMounted(() => {
  if (monitorEnabled.value) {
    setupDefaultObservers()
    setupPerformanceMonitoring()
  }
  updateObserverStats()
})
</script>

<style scoped>
.route-observer-monitor {
  padding: 20px;
}

.monitor-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-section {
  padding: 16px 0;
}

.observers-section {
  padding: 16px 0;
}

.history-section {
  padding: 16px 0;
}

.history-actions {
  margin-bottom: 16px;
}

.history-item {
  margin-bottom: 8px;
}

.route-info {
  padding: 8px;
}

.route-path {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 4px;
}

.route-meta {
  font-size: 12px;
  color: #909399;
}

.route-meta span {
  margin-right: 12px;
}

.performance-section {
  padding: 16px 0;
}

.debug-section {
  padding: 16px 0;
}

.debug-info {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 16px;
  font-size: 12px;
  line-height: 1.5;
  max-height: 400px;
  overflow-y: auto;
}

.el-timeline {
  max-height: 400px;
  overflow-y: auto;
}
</style>